<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPig;
use common\components\Upload;
use Yii;
use common\models\sys\SysSetting;
use backend\modules\business\models\SysSettingSearch;
use yii\db\Query;
use yii\helpers\FileHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SysSettingController implements the CRUD actions for SysSetting model.
 */
class SettingController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all SysSetting models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SysSettingSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single SysSetting model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SysSetting model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SysSetting();

        if(Yii::$app->request->isPost){
            $postdata = Yii::$app->request->post();
            if(empty($postdata['keyvalue']) || empty($postdata['keyname'])){
                return $this->dialog('请填写必要项');
            }
            $date['keyvalue'] = implode('||',$postdata['keyvalue']);
            $data['keyname']=  $postdata['keyname'];

            if(Yii::$app->user->id == '1'){
                $data['canuser']=  $postdata['SysSetting']['canuser'];

            }

            $res = Yii::$app->db->createCommand()->insert(SysSetting::tableName(),$data)->execute();

            return $res?$this->timeAlert('添加成功','index'):$this->timeAlert('添加失败');
        }else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing SysSetting model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $user = (new Query())->select('identify')->from(SysSetting::tableName())->where('canuser=:can and identify=:id',[':can'=>Yii::$app->user->id,':id'=>$id])->one();

        if(Yii::$app->user->identity->id != 1 && Yii::$app->user->identity->id != 5){
            if(!$user){
                return $this->dialog('对不起，您没有权限');
            }
        }


        if(Yii::$app->request->isPost){
            $postdata = Yii::$app->request->post();
            if($model->viewtype == SysSetting::TYPE_INPUT){
                if(empty($postdata['keyvalue']) || empty($postdata['keyname'])){
                    return $this->dialog('请填写必要项');
                }

                //过滤掉空值
                foreach ($postdata['keyvalue'] as $key => $row){
                    if(empty($row)){
                        unset($postdata['keyvalue'][$key]);
                    }
                }
                $data['keyvalue'] = implode('||',$postdata['keyvalue']);

                if(Yii::$app->user->id == '1'){
                    $data['canuser']=  $postdata['SysSetting']['canuser'];
                }

            }else{
                $model->load($postdata);

                if(empty($postdata['keyname'])){
                    return $this->dialog('请填写必要项');
                }
                if(Yii::$app->user->id == '1'){
                    $data['canuser']=  $postdata['SysSetting']['canuser'];
                }

                if($model->viewtype == SysSetting::TYPE_FILE){      //文件
                    Upload::deleteImg($model->getOldAttribute('keyvalue'));
                    if(false !== $photo = Upload::upload($model,'keyvalue')){
                        $data['keyvalue'] = $photo;
                    }
                }else if($model->viewtype == SysSetting::TYPE_COLOR){       //颜色
                    $default = [        //默认颜色
                        'mobile_theme_color' => '#569938',       //主体
                        'mobile_theme_search_color' => '#277306'      //头部搜索框
                    ];
                    $data['keyvalue'] = $postdata['SysSetting']['keyvalue'];
                    if(empty($model->getOldAttribute('keyvalue'))){
                        $search = $default[$id];
                    }else{
                        $search = $model->getOldAttribute('keyvalue');
                    }

                    $stylecontent = file_get_contents(Yii::getAlias('@frontend').'/web/static/css/mobile.css');
                    $stylecontent = str_replace($search,$data['keyvalue'],$stylecontent);
                    $res = file_put_contents(Yii::getAlias('@frontend').'/web/static/css/mobile.css',$stylecontent);
                }
            }


            $data['keyname']=  $postdata['keyname'];
            $res = Yii::$app->db->createCommand()->update(SysSetting::tableName(),$data,'identify=:keyname',[':keyname'=>$id])->execute();
            return $res || $res==0?$this->timeAlert('添加成功','index'):$this->timeAlert('添加失败');
        } else {
            if($model->viewtype == SysSetting::TYPE_INPUT){
                $model->keyvalue = explode('||',$model->keyvalue);
            }
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing SysSetting model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SysSetting model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return SysSetting the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = SysSetting::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
